package com.tanhua.sso.service;

import com.aliyun.oss.OSSClient;
import com.tanhua.sso.config.AliyunOSSConfig;
import com.tanhua.sso.vo.PicUploadResult;
import org.apache.commons.lang3.RandomUtils;
import org.apache.commons.lang3.StringUtils;
import org.joda.time.DateTime;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.ByteArrayInputStream;

@Service
public class PicUploadService {

    // 允许上传的格式
    private static final String[] IMAGE_TYPE = new String[]{".bmp", ".jpg", ".jpeg", ".gif", ".png"};

    @Autowired
    private OSSClient ossClient;

    @Autowired
    private AliyunOSSConfig aliyunOSSConfig;

    /**
     * 文件上传
     * @param uploadFile 文件对象
     * @return 上传结果
     */
    public PicUploadResult upload(MultipartFile uploadFile) {
        //创建上传结果对象，用来存储上传结果
        PicUploadResult fileUploadResult = new PicUploadResult();
        //图片做校验，对后缀名
        boolean isLegal = false;
        //遍历格式数组
        for (String type : IMAGE_TYPE) {
            //判断上传文件的文件名，是否以指定后缀名作为结尾
            if (StringUtils.endsWithIgnoreCase(uploadFile.getOriginalFilename(), type)) {
                //如果符合任意一种格式，则修改isLegol为true
                isLegal = true;
                break;
            }
        }
        //如果不是，则表示上传失败
        if (!isLegal) {
            fileUploadResult.setStatus("error");
            return fileUploadResult;
        }

        // 文件新路径
        String fileName = uploadFile.getOriginalFilename();
        String filePath = getFilePath(fileName);

        // 上传到阿里云
        try {
            // 目录结构：images/2018/12/29/xxxx.jpg
            ossClient.putObject(aliyunOSSConfig.getBucketName(), filePath, new ByteArrayInputStream(uploadFile.getBytes()));
        } catch (Exception e) {
            e.printStackTrace();
            //上传失败
            fileUploadResult.setStatus("error");
            return fileUploadResult;
        }

        // 上传成功
        fileUploadResult.setStatus("done");
        fileUploadResult.setName(aliyunOSSConfig.getUrlPrefix() + filePath);
        fileUploadResult.setUid(String.valueOf(System.currentTimeMillis()));

        return fileUploadResult;
    }

    /**
     * 获取文件存储路径
     * @param sourceFileName 文件名
     * @return 文件的存储位置
     */
    private String getFilePath(String sourceFileName) {
        DateTime dateTime = new DateTime();
        return "images/" + dateTime.toString("yyyy")
                + "/" + dateTime.toString("MM") + "/"
                + dateTime.toString("dd") + "/" + System.currentTimeMillis() +
                RandomUtils.nextInt(100, 9999) + "." +
                StringUtils.substringAfterLast(sourceFileName, ".");
    }
}
